-
-
Notifications
You must be signed in to change notification settings - Fork 33.1k
gh-139772: Add PyDict_FromItems() function #139963
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
For consuming from PyO3 / Rust, I can see this function being obviously useful for cases of small dictionaries with statically known keys (think producing things that look like I think for arbitrary-sized collections, it's probably the case (in Rust) that either:
|
Do you mean producing an array of |
Adding this function would avoid having to make the private PyObject *
_PyStack_AsDict(PyObject *const *values, PyObject *kwnames)
{
Py_ssize_t nkwargs;
assert(kwnames != NULL);
nkwargs = PyTuple_GET_SIZE(kwnames);
return _PyDict_FromItems(&PyTuple_GET_ITEM(kwnames, 0), 1,
values, 1, nkwargs);
} |
I was thinking more like 2-tuples, the type might be written in Rust as The 2-tuples are quite a natural structure for Rust producers of "items" (it's what they would expect when iterating a mapping type, for example). But maybe the more common case would be the second one I suggest - a rust iterator producing item 2-tuples with a size hint. At the moment we just start from I could of course use the |
Or name the function in this PR Note that the current private The case of building small literal dicts could also use a
That's really not much different from |
Co-authored-by: scoder <stefan_ml@behnel.de>
I think it's ok, the individual tuple items are pointers and so will be aligned appropriately. AFAIK Rust is allowed to reorder tuples to improve packing but guarantees all elements are properly aligned for their type.
True, just that we try not to use private APIs at all in PyO3 so having a public API for this would open up the possibility to use it in PyO3. I understand there's a question about what to do about the unicode optimization with the "presized" API, I suggest we just make it roughly match whatever a normal Python dict would do if created empty and then had items repeatedly added (with the exception that the storage is preallocated). |
So you would prefer this API? PyObject *
PyDict_FromItems(PyObject *const *keys, Py_ssize_t keys_offset,
PyObject *const *values, Py_ssize_t values_offset,
Py_ssize_t length) |
In short, you would prefer #139773 API? |
📚 Documentation preview 📚: https://cpython-previews--139963.org.readthedocs.build/